%%%-------------------------------------------------------------------
%%% @author root
%%% @copyright (C) 2016, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 14. 二月 2016 下午8:52
%%%-------------------------------------------------------------------
-module(cus_emotion_packet_edit_handler).
-behaviour(cowboy_http_handler).

-include("cus.hrl").

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).




init(_Type, Req, _Opts) ->
  {ok, Req, undefined_state}.

handle(Req, State) ->
  {Method,_} = cowboy_req:method(Req),
  HasBody = cowboy_req:has_body(Req),
  {CookieVal, Req2} = cowboy_req:cookie(<<"sessionid">>, Req),
%%  check SessionID and refresh cookie
  case cus_util:filter(CookieVal) of
    {true,UserName, PassWord} ->
      SessionID = cus_util:get_session_id(UserName,PassWord),
      Req3 = cowboy_req:set_resp_cookie(<<"sessionid">>, SessionID, [
        {max_age, ?COOKIE_TIME}
      ], Req2),
      {ok,Req4} = maybe_echo(Method, HasBody, Req3),
      {ok, Req4, State};
    _->
      {ok, Body} = login_dtl:render([
      ]),
      {ok,Req3} = echo(Body, Req2),
      {ok, Req3, State}
  end.

terminate(_Reason, _Req, _State) ->
  ok.

maybe_echo(<<"GET">>, false, Req) ->
  {Id,Req2} = cowboy_req:qs_val(<<"id">>,Req),
 case Id of
   undefined ->
     IdList1 =[Packet#cus_sys_emotion_packet.id||Packet<- cus_redis:get_sys_emotion_packets()],
     SeqIdList = case IdList1 of
                   [] ->
                     [];
                   _->
                     lists:seq(1,?l2i(lists:max(IdList1)))
                 end,
     Data = [[Packet#cus_sys_emotion_packet.id,
       Packet#cus_sys_emotion_packet.name,
       Packet#cus_sys_emotion_packet.displayOrder,
       Packet#cus_sys_emotion_packet.directory,
       Packet#cus_sys_emotion_packet.available,
       Packet#cus_sys_emotion_packet.cover,
       Packet#cus_sys_emotion_packet.code,
       Packet#cus_sys_emotion_packet.detail,
       Packet#cus_sys_emotion_packet.emotions]||Packet <-lists:reverse(cus_util:get_emotion_packets(SeqIdList,[]))],
     {ok, Body} = cus_emotion_packet_list_dtl:render([
       {data,Data}
     ]),
     echo(Body, Req2);

   _->
     Packet =cus_redis:get_sys_emotion_packet(Id),
     DisplayOrders1 = [{Packet1#cus_sys_emotion_packet.displayOrder++"_"}||Packet1 <- cus_redis:get_sys_emotion_packets()],
     DisplayOrders2 = lists:keydelete(Packet#cus_sys_emotion_packet.displayOrder++"_",1,DisplayOrders1),
     DisplayOrders = [tuple_to_list(DisplayOrder)||DisplayOrder <- DisplayOrders2],
     {ok, Body} = cus_emotion_packet_add_dtl:render([
       {displayOrders,DisplayOrders},
       {id, Packet#cus_sys_emotion_packet.id},
       {name, Packet#cus_sys_emotion_packet.name},
       {displayOrder, Packet#cus_sys_emotion_packet.displayOrder},
       {directory, Packet#cus_sys_emotion_packet.directory},
       {available, Packet#cus_sys_emotion_packet.available},
       {cover, Packet#cus_sys_emotion_packet.cover},
       {code, Packet#cus_sys_emotion_packet.code},
       {detail, Packet#cus_sys_emotion_packet.detail},
       {emotions, Packet#cus_sys_emotion_packet.emotions}
     ]),
     echo(Body, Req2)
 end;


maybe_echo(<<"POST">>, true, Req) ->
  {ok, PostVals, Req2} = cowboy_req:body_qs(Req),
  Id =?param(<<"id">>,PostVals),
  Packet =cus_redis:get_sys_emotion_packet(Id),
  NewPacket = Packet#cus_sys_emotion_packet{
                               name=?param(<<"name">>,PostVals),
                       displayOrder=?param(<<"displayOrder">>,PostVals),
                          directory=?param(<<"directory">>,PostVals),
                          available=?param(<<"available">>,PostVals),
                              cover=?param(<<"cover">>,PostVals),
                               code=?param(<<"code">>,PostVals),
                             detail=?param(<<"detail">>,PostVals)},
  cus_redis:set_sys_emotion_packets(NewPacket),

  IdList1 =[Packet1#cus_sys_emotion_packet.id||Packet1<- cus_redis:get_sys_emotion_packets()],
  SeqIdList = case IdList1 of
                [] ->
                  [];
                _->
                  lists:seq(1,?l2i(lists:max(IdList1)))
              end,
  Data = [[Packet2#cus_sys_emotion_packet.id,
           Packet2#cus_sys_emotion_packet.name,
           Packet2#cus_sys_emotion_packet.displayOrder,
           Packet2#cus_sys_emotion_packet.directory,
           Packet2#cus_sys_emotion_packet.available,
           Packet2#cus_sys_emotion_packet.cover,
           Packet2#cus_sys_emotion_packet.code,
           Packet2#cus_sys_emotion_packet.detail,
           Packet2#cus_sys_emotion_packet.emotions]||Packet2 <-lists:reverse(cus_util:get_emotion_packets(SeqIdList,[]))],

  {ok, Body} = cus_emotion_packet_list_dtl:render([
      {data,Data}
      ]),
  echo(Body, Req2);




maybe_echo(<<"POST">>, false, Req) ->
  {ok, Body} = failed_dtl:render([
    {errorMsg,"Missing body"}
  ]),
  cowboy_req:reply(400, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req);
maybe_echo(_, _, Req) ->

  {ok, Body} = failed_dtl:render([
    {errorMsg,"405"}
  ]),
  cowboy_req:reply(405, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req).


echo(undefined, Req) ->
  {ok, Body} = failed_dtl:render([
    {errorMsg,"system error"}
  ]),
  cowboy_req:reply(400, [{<<"content-type">>, <<"text/html; charset=utf-8">>}], Body, Req);
echo(Body, Req) ->
  cowboy_req:reply(200, [
    {<<"content-type">>, <<"text/html; charset=utf-8">>}
  ], Body, Req).

